package com.chat.netty;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

public class WSServerInitializer extends ChannelInitializer<SocketChannel> {
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        //得到pipeline句柄
        ChannelPipeline pipeline = socketChannel.pipeline();

        //添加支持Http协议需要的 Handler
        pipeline.addLast(new HttpServerCodec());
        //对写大数据流的支持
        pipeline.addLast(new ChunkedWriteHandler());
        //对httpMessage进行聚合，聚合城FullHttpRequest或者FullHttpResponse
        pipeline.addLast(new HttpObjectAggregator(1024*64));

        // =================================上面是为了支持http协议所添加的处理类==================================

        /**
         * 指定了给客户端访问的路由: /ws
         * 此handler会帮你处理一些繁杂的事
         * 比如：握手动作，心跳
         * 对于websocket来讲，都是以frames进行传输的,不同数据类型对应的frames不同
         */
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));

        /// TODO 自定义Handler
        pipeline.addLast(new com.chat.netty.ChatHandler());
    }
}
